<template>
	<view class="page-view">
		<view class="top-pane">
			<view class="index-title-bg">
				<view class="u-p-l-30 u-p-r-30">
					<view class="logo">
						<u-image src="/static/logo_s.png" mode="widthFix" width="100%" :showMenuByLongpress="false"
							:showLoading="false" :fade="false"></u-image>
					</view>
					<view class="switch-map" @click="switchMapHandle">
						<view class="u-flex switch-item u-col-center">
							<view class="u-flex-1 align-center" :class="showMap?'white':''">地图</view>
							<view class="u-flex-1 align-center" :class="!showMap?'white':''">列表</view>
						</view>
						<view class="item-bg" :class="showMap?'left':'right'"></view>
					</view>
					<view class="u-flex u-col-center u-row-between u-m-b-20">
						<view class="">
							<bb-search :city="city" @toLocation="toLocation" :show-btn="false" placeholder="可搜索任务需求"
								@seachTap="$u.route('/pages/subpage/search/index',{type:2})"></bb-search>
						</view>

						<u-button type="primary" size="medium" shape="circle" hover-class="none" :custom-style="customStyle"
							@click="navtoDemand('/pages/subpage/publish/demand')">
							<u-icon name="plus" color="#FFFFFF" size="24"></u-icon>
							<text>发需求</text>
						</u-button>
					</view>
				</view>

				<view class="u-flex u-p-r-30">
					<view class="u-flex-1" style="width: 0;">
						<bb-tabs :list="tabList" :current="current" @change="change"></bb-tabs>
					</view>
					<view class="sort-select" @click="openDropdown" v-if="!showMap">
						综合
						<text class="iconfont icon-xiala "></text>
					</view>
				</view>
			</view>
			<view class="dropdown-menu" :class="[showdrop?'open':'']">
				<view class="slot-content">
					<view class="item-box placeholder">
						<view class="item" :class="[orderBy==item.value?'active':'']" v-for="(item,index) in sortOptions"
							:key="index" @tap="tagClick(item.value)">{{item.label}}
						</view>
					</view>
					<view class="u-flex">
						<u-button type="default" size="medium"
							:customStyle="{borderColor: '#cccccc',color: '#999999', width:'227rpx'}" plain hover-class="none"
							shape="circle" @click="resetSort()">重置</u-button>
						<view class="u-flex-1 u-m-l-24">
							<u-button type="primary" size="medium" :customStyle="{ width:'100%'}" hover-class="none" shape="circle"
								@click="refirshData()">确定</u-button>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="content-list">
			<u-mask :show="showdrop" @click="showdrop = false" z-index="9"></u-mask>
			<mescroll-uni @init="mescrollInit" @down="downCallback" @up="upCallback" top="352" v-show="!showMap"
				:up="upOption" @emptyclick="navtoDemand('/pages/subpage/publish/demand')">
				<view class="u-m-30" v-for="(item,index) in demandList" :key="index">
					<bb-demand :info="item"></bb-demand>
				</view>
			</mescroll-uni>
			<view class="map-view" v-show="showMap">
				<!-- #ifdef MP -->
				<map id="MapView" ref="MapView" style="width: 750rpx;height: 1250rpx;" show-compass show-location
					enable-building :scale="scale" enable-3D :latitude="Number(currentGPS[1])" :longitude="Number(currentGPS[0])"
					:markers="markers" @callouttap="markerTapHandle" @tap="mapTapHandle">

					<cover-view class="current-location" @click="resetView">
						<cover-image src="/static/location.png" class="icon"></cover-image>
					</cover-view>
				</map>
				<!-- #endif -->
				<!-- #ifdef APP || H5 -->
				<view id='amap' :style="mapStyle">
				</view>
				<cover-image :markers="markers" :location="currentGPS" :change:location="aMapRenderJs.getLocation"
					:change:markers="aMapRenderJs.getmarkers"></cover-image>
				<!-- #endif -->
				<view class="select-power" v-if="seletMarkPower.id">
					<bb-demand :info="seletMarkPower"></bb-demand>
				</view>
			</view>
		</view>
	</view>
</template>


<script>
	const sortOptions = [{
			label: '不限',
			value: '',
		},
		{
			label: '发布时间',
			value: 'time',
		},
		{
			label: '价格',
			value: 'price',
		},
		{
			label: '距离',
			value: 'location',
		}
	]
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	import config from '@/config.js'
	var wv;
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				customStyle: {
					width: "160rpx"
				},
				sortType: 1,
				current: 0,
				sortOptions: sortOptions,
				tabList: [],
				city: this.$store.state.vuex_address.city || config.D_CITY,
				location: this.$store.state.vuex_address.location || config.D_LOC,
				page: 1,
				limit: 10,
				demandList: [],
				classId: '',
				showdrop: false,
				orderBy: '',
				showMap: false,
				markers: [],
				scale: 12,
				mapContext: null,
				currentGPS: [],
				seletMarkPower: {},
				mapStyle: {
					width: '750rpx',
					height: '780px'
				},
				upOption: {
					empty: {
						tip: "暂时没有相关需求哦~",
						btnText: "我要发布"
					}
				}
			}
		},
		onShow() {
			uni.$off('selectLocation')
			if (this.canUse) {
				this.mescroll.resetUpScroll();
			}
			this.canUse = true
		},
		onLoad() {
			this.querClasslist()
			this.currentGPS = this.location.split(',')

		},
		onReady() {
			// #ifdef MP
			this.mapContext = uni.createMapContext('MapView', this);
			this.mapContext.setCenterOffset({
				offset: [0.5, 0.4]
			})
			// #endif
		},
		mounted() {
			setTimeout(() => {
				this.listContentRect()
			}, 300)
		},
		methods: {
			listContentRect() {
				const query = uni.createSelectorQuery().in(this);
				query
					.select(".content-list")
					.boundingClientRect((data) => {
						const systemInfo = this.$store.state.vuex_sysmbelInfo;
						let tabBarHeight = systemInfo.screenHeight - systemInfo.safeArea.bottom;; // TabBar的高度
						// #ifdef H5
						tabBarHeight = 50
						// #endif
						this.mapStyle.height = (data.height - tabBarHeight) + 'px';
					})
					.exec();
			},
			switchMapHandle() {
				this.showMap = !this.showMap
				if (this.showMap && this.markers.length == 0) {
					this.getALlMarkers()
				}
			},
			imageLoad(index) {
				setTimeout(() => {
					this.$set(this.markers[index], 'show', true)
					this.markers[index].show = true
				}, 10)
			},
			// 复位地图
			resetView() {
				this.seletMarkPower = {}
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						const {
							latitude,
							longitude
						} = res;
						this.mapContext.moveToLocation({
							latitude,
							longitude
						})
					}
				})
			},
			// 点击marker
			markerTapHandle(e) {
				this.seletMarkPower = {}
				setTimeout(() => {
					const {
						markerId
					} = e.detail;
					const powerItem = this.markers.find(item => item.id == markerId);
					this.seletMarkPower = powerItem.info;
				}, 300)
			},
			// 点击地图
			mapTapHandle() {
				this.seletMarkPower = {}
			},
			openDropdown() {
				this.showdrop = !this.showdrop
			},
			tagClick(value) {
				this.orderBy = value
			},
			resetSort() {
				this.orderBy = ''
				this.showdrop = false;
				this.mescroll.resetUpScroll();
			},
			refirshData() {
				this.showdrop = false;
				this.mescroll.resetUpScroll();
			},
			upCallback(page) {
				this.queryDemand(page)
			},
			change(index) {
				this.current = index
				this.classId = this.tabList[index].id;
				this.mescroll.resetUpScroll();
				if (this.showMap) {
					this.markers = []
					this.getALlMarkers()
				}
			},
			queryDemand(page) {
				this.$u.api.public.demand_lst({
					location: this.location,
					order: this.orderBy,
					page: page.num,
					limit: page.size,
					class_one_id: this.classId
				}).then(res => {
					this.demandList = page.num == 1 ? res : [...this.demandList, ...res];

					this.mescroll.endSuccess(res.length, res.length >= page.size);
				})
			},
			querClasslist() {
				this.$u.api.public.industry_class({
					pid: 0,
					type: 'demand'
				}).then(res => {
					this.tabList = [{
						id: '',
						name: '全部'
					}, ...res];
					console.log('加载分类');
					// this.mescroll.resetUpScroll();
				})
			},
			toLocation() {
				uni.$on('selectLocation', (data) => {
					console.log('dm:', data);
					const {
						city,
						location
					} = data
					this.city = city
					this.location = location
					this.page = 1;
					this.mescroll.resetUpScroll();
				})
				this.$u.route('/pages/subpage/list/location')
			},
			navtoDemand(path) {
				const userInfo = this.$store.state.vuex_userInfo;
				if (userInfo && userInfo.is_real) {
					this.$u.route(path)
				} else {
					this.$u.route('/pages/subpage/profile/autonym')
				}
			},
			getALlMarkers(num = 1, size = 10) {
				this.$u.api.public.demand_lst({
					location: this.location,
					order: this.orderBy,
					freeType: this.filter,
					page: num,
					limit: size,
					class_one_id: this.classId
				}).then(res => {
					const markers = res.map(item => {
						return {
							id: item.id,
							title: item.title,
							width: 1,
							height: 1,
							latitude: Number(item.lat),
							longitude: Number(item.lng),
							iconPath: '/static/1.png',
							show: false,
							info: item,
							callout: {
								display: "ALWAYS",
								content: '￥' + item.price,
								color: '#FFAA44',
								fontSize: 16,
								borderRadius: 5,
								textAlign: 'center',
								padding: 4,
								bgColor: '#fff'
							}
						};
					})
					this.markers = num == 1 ? markers : [...this.markers, ...markers];
					if (markers.length >= size) {
						num++;
						this.getALlMarkers(num)
					}
				})
			}
		},

	}
</script>
<!-- #ifndef MP -->
<!-- 高德地图 web api -->
<!-- 地图引入高德 使用renderjs 引入 对renderjs不了解 可以看着案例去弄 -->
<script module="aMapRenderJs" lang="renderjs">
	const A_MAP_KEY = "dc9679975db6077a9e49b5e4b11a7867"; // 地图key
	const A_MAP_SECRET_KEY = "63d08bb686f7e70f689f937e11bb6ae2"; // 地图密钥

	export default {
		data() {
			return {
				map: null,
				markersList: [],
				location: []
			}
		},
		mounted() {
			this.getmarkers()
			// 地图初始化 
			if (typeof window.AMap === 'function') {
				this.initAmap();
			} else {
				window._AMapSecurityConfig = {
					securityJsCode: A_MAP_SECRET_KEY,
				};
				const script = document.createElement('script');
				script.src = `https://webapi.amap.com/maps?v=2.0&key=${A_MAP_KEY}&plugin=AMap.Walking`;
				script.onload = this.initAmap.bind(this);
				document.head.appendChild(script);
			}
		},
		methods: {
			// 获取 外卖员的数据
			getmarkers(e) {
				this.map && this.map.clearMap();

				if (e && e.length > 0) {
					this.markersList = e;
					this.drawMarks()
				}
			},
			getLocation(e) {
				if (e) {
					this.location = e.map(item => Number(item))
				}
			},
			// 初始化
			initAmap() {
				this.map = new AMap.Map('amap', {
					resizeEnable: true,
					zoom: 12,
					center: this.location, //初始化地图中心点位置
				})
				this.map.on('click', () => {
					this.$ownerInstance.callMethod('mapTapHandle')
				})
				AMap.plugin('AMap.Geolocation', () => {
					const geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, //是否使用高精度定位，默认:true
						timeout: 10000, //超过10秒后停止定位，默认：5s
						position: 'RB', //定位按钮的停靠位置
						offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
						zoomToAccuracy: false, //定位成功后是否自动调整地图视野到定位点
						panToLocation: true
					});
					this.map.addControl(geolocation);
					geolocation.getCurrentPosition((status, result) => {
						this.$ownerInstance.callMethod('mapTapHandle')
						if (status == 'complete') {
							console.log(result);
						} else {
							console.log(result)
						}
					});
				})
			},
			drawMarks() {
				console.log('重回，', this.markersList.length);
				let that = this
				// 遍历 marker位置
				that.markersList.forEach(item => {
					// const wicon = new AMap.Icon({
					// 	size: new AMap.Size(1, 1), // 图标尺寸
					// 	image: "/", // Icon的图像
					// 	imageSize: new AMap.Size(1, 1) // 根据所设置的大小拉伸或压缩图片
					// });
					const wcontent =
						"<div class='u-type-warning price radius10 bg-white u-p-l-10 u-p-r-10 box-shadow' >" +
						item.info.price + "</div>";
					const wmarkert = new AMap.Marker({
						content: wcontent, // 自定义点标记覆盖物内容
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(0, -2), // 相对于基点的偏移位置
						anchor: "bottom-center",
						extData: {
							markerId: item.info.id
						}
					});
					wmarkert.on('click', (e) => {
						const extData = e.target.getExtData()
						that.$ownerInstance.callMethod('markerTapHandle', {
							detail: extData
						})
					})
					that.map.add(wmarkert);
					const pointContent = `<div class="marker-callout"><div>`
					const wmarker = new AMap.Marker({
						position: [item.longitude, item.latitude],
						offset: new AMap.Pixel(-2, -2),
						content: pointContent, // 添加 Icon 实例
					});
					that.map.add(wmarker);
				})
			}
		}
	}
</script>
<!-- #endif -->
<style lang="scss">
	.marker-callout {
		position: relative;

		&:after {
			content: '';
			display: block;
			position: absolute;
			border: 4px solid #fff;
			border-left-color: transparent;
			border-right-color: transparent;
			border-bottom-color: transparent;
			// transform: rotateZ(45deg);
		}
	}
</style>
<style lang="scss" scoped>
	.page-view {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.top-pane {
		background-color: #FFFFFF;
		// position: sticky;
		top: 0;
		width: 100%;
		z-index: 99;
	}

	.content-list {
		flex: 1;
		height: 0;
		overflow: hidden;
	}

	.index-title-bg {
		background: linear-gradient(175deg, $u-type-primary-light -150%, #FFFFFF 70%, #FFFFFF 100%);
		padding-top: 3rpx;
	}

	.logo {
		width: 136rpx;
		margin-top: 90rpx;
		margin-left: 5rpx;
		margin-bottom: 30rpx;
	}

	.sort-select {
		width: 200rpx;
		height: 60rpx;
		background: #F6F6F6;
		border-radius: 50rpx 50rpx 50rpx 50rpx;
		margin-bottom: 10rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 30rpx;
		color: #666666;
		font-size: 28rpx;

		.iconfont {
			font-size: 10rpx;
		}
	}

	.dropdown-menu {
		position: absolute;
		width: 100%;
		height: 0;
		z-index: 999;
		transition: all 0.3s;
		overflow: hidden;

		&.open {
			height: 420rpx;
		}
	}

	.slot-content {
		background-color: #FFFFFF;
		padding: 30rpx;

		.item-box {
			margin-bottom: 60rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			&.placeholder:after {
				content: '';
				display: block;
				width: 180rpx;
			}

			.item {
				color: $u-tips-color;
				width: 180rpx;
				height: 60rpx;
				background: #EFEFEF;
				border-radius: 80rpx 80rpx 80rpx 80rpx;
				line-height: 60rpx;
				text-align: center;
				margin-bottom: 30rpx;
			}

			.active {
				color: $u-type-primary;
				background-color: #E5FEEB;
			}
		}
	}

	.switch-map {
		position: fixed;
		top: 90rpx;
		left: 290rpx;
		z-index: 99;
	}

	.map-view {
		height: 100%;
	}

	.current-location {
		position: absolute;
		bottom: 100rpx;
		right: 30rpx;
		background-color: #fff;
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
		box-shadow: 1px 1px 16rpx 0px rgba(0, 101, 77, 0.1);
		display: flex;
		align-items: center;
		justify-content: center;

		.icon {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.select-power {
		position: fixed;
		left: 30rpx;
		right: 30rpx;
		bottom: 180rpx;
	}
</style>